package cn.web.download;

import cn.web.utils.DownLoadUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/downloadServlet")
public class downloadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       // 获取参数名称
        String filename = request.getParameter("filename");
        // 根据参数找到文件的位置，并将其读进内存
        ServletContext servletContext = this.getServletContext();   // new一个真实路径对象
        String realPath = servletContext.getRealPath("/DownloadResource/" + filename);  // 获取真实路径
        // 字节流读取
        FileInputStream fileInputStream = new FileInputStream(realPath);
        // 设置response响应头
        response.setContentType(servletContext.getMimeType(filename));//设置response，告知浏览器用什么方式解码，解码和编码的类型必须得一直，所以要将文件的mime类型传递给客户端
        String header = request.getHeader("user-agent");// 获取客户端的浏览器版本
        String fileName = DownLoadUtils.getFileName(header, filename);   // 将资源名变成浏览器可以解析的格式
        response.setHeader("content-disposition","attachment;filename="+fileName); // 以附件形式打开
        ServletOutputStream outputStream = response.getOutputStream();// 把数据从内存中写入到输出流
        byte[] buff =new byte[1024*8];// 设置缓冲区
        int len=0;
        while ((len=fileInputStream.read(buff))!=-1){
            outputStream.write(buff,0,len);
        }




    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                this.doPost(request,response);
    }
}
